//
//  CityCommunityDetailViewController.m
//  cityStar
//
//  Created by joyban on 15-3-9.
//  Copyright (c) 2015年 tiny. All rights reserved.
//

#import "CityCommunityDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "ReleasViewController.h"
#import "WritePostViewController.h"
#import "SVPullToRefresh.h"

@interface CityCommunityDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSArray *requestArray;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *arrayRequest;

@end

@implementation CityCommunityDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"帖子详情";
    [self addBackButton];
    __weak typeof(self)weakSelf = self;
    [self addRightButtonWithTitle:@"发贴" actionBlock:^{
        WritePostViewController *postVC = [[WritePostViewController alloc]init];
        [weakSelf.navigationController pushViewController:postVC animated:YES];
    }];
    self.requestArray = [[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil];
    self.arrayRequest = [[NSMutableArray alloc]init];
    [self webRequest_getBBSDetails];
    [self.tableView addPullToRefreshWithActionHandler:^{
        self.page = 1;
        [weakSelf webRequest_GetlistMore:NO];
    }];
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf webRequest_GetlistMore:YES];
    }];
    [self.tableView triggerPullToRefresh];
    [self setUpViews];
}

-(void)webRequest_GetlistMore:(BOOL)isMore
{
    NSString *postUrl = [NSString stringWithFormat:@"%@/page/%i/id/%@",KInterface_Getcomment,isMore?self.page:0,self.copmodel.objectId];
    [HttpRequestManager getMethod:[postUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        DLog(@"%@",response);
        if (success) {
            if (isMore) {
                [self.arrayRequest addObjectsFromArray:response[@"value"][@"content"]];
                self.page = self.page + 1;
            }else{
                self.arrayRequest = [[NSMutableArray alloc]initWithArray:response[@"value"][@"content"]];
            }
            [self.tableView reloadData];

        }
        if (isMore) {
            [self.tableView.infiniteScrollingView stopAnimating];
        }else{
            [self.tableView.pullToRefreshView stopAnimating];
        }
    }];
}

#pragma mark - setUps
-(void)setUpViews
{
    self.scrollView.contentSize = CGSizeMake(AppBounds.size.width, 580);
    NSString *labelStr = @"没羞没臊没看见是你的仓科加奈心就开始你下课就辛苦的几十年技能书的科技城尽可能触手可及内存卡接收到你苍井空就能看小树林快门线";
    self.labelTitle.font = [UIFont systemFontOfSize:14];
    [self.labelTitle setLineBreakMode:NSLineBreakByWordWrapping];
    [self.labelTitle setNumberOfLines:0];
    self.labelTitle.text = labelStr;
    [self.labelTitle sizeToFit];
    self.imageContent.frame = CGRectMake(15, self.labelTitle.y+self.labelTitle.height+8, 190, 115);
    self.imageContent.image = [UIImage imageNamed:@"商品列表_img"];
    self.tableView.frame = CGRectMake(15, self.imageContent.y+self.imageContent.height+14, CGRectGetWidth(AppBounds)-30, self.requestArray.count*30);
    self.belowView.frame = CGRectMake(0, self.imageContent.y+self.imageContent.height+self.requestArray.count*30, CGRectGetWidth(AppBounds), 30);
    
    self.labelTitle.text = self.copmodel.content;
    self.namelabel.text = self.copmodel.creator_name;
    NSString * imagePath = @"";
    imagePath = [NSString stringWithFormat:@"%@",self.copmodel.avatar];
    [self.heardimage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.icszx.com/image/c/id/%@/w/30/h/30/m/0",imagePath]] placeholderImage:[UIImage imageNamed:@"品牌列表_主图"]];
    NSString * imagePathTwo = [NSString stringWithFormat:@"%@",self.copmodel.image];
    if(![imagePathTwo isEqualToString:@"0"])
    {
        NSString * imagePathThree = [NSString stringWithFormat:@"%@",self.copmodel.image[0]];
        [self.imageContent sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://api.icszx.com/image/c/id/%@/w/190/h/110/m/0",imagePathThree]] placeholderImage:[UIImage imageNamed:@"商品列表_img"]];
        
    }
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[[NSString stringWithFormat:@"%@",self.copmodel.create_time] intValue]];
        self.timelabel.text = [self dateStringFromNow:confromTimesp];
    [self.citylabel setTitle:self.copmodel.community_name forState:UIControlStateNormal];
}

-(NSString*)dateStringFromNow:(NSDate*)date{
    NSTimeInterval time = -[date timeIntervalSinceNow];
    if (time<0) {
        return @"";
    }else {
        if (time<3600*24) {
            if (time>=0.0 && time <60.0) {
                return @"刚刚";
            }else if (time>=60.0 && time <60.0*60.0) {
                return [NSString stringWithFormat:@"%d分钟前",(int)time/60];
            }else if (time>=3600.0 && time <3600.0*24) {
                return [NSString stringWithFormat:@"%d小时前",(int)time/3600];;
            }
        }else {
            
            NSCalendar* calendar = [NSCalendar currentCalendar];
            NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSWeekCalendarUnit fromDate:date toDate:[NSDate date] options:0];
            if ([components year]>0) {
                int month = [components year]*12+[components month];
                return [NSString stringWithFormat:@"%d月前",month];
            }else if([components month]>0){
                int month = [components month];
                return [NSString stringWithFormat:@"%d月前",month];
            }else if([components week]>0){
                return [NSString stringWithFormat:@"%d周前",[components week]];
            }else if([components day]>0){
                return [NSString stringWithFormat:@"%d天前", [components day]];
            }
        }
    }
    return @"";
}

#pragma mark - WebRequest
-(void)webRequest_getBBSDetails
{
    NSString *postUrl = [NSString stringWithFormat:@"%@%@",KinterFace_CommunityBBSdetail,self.copmodel.objectId];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if (success) {
            DLog(@"%@",response);
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

#pragma mark - tableView Deleagte and DateSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"NoticeTableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    cell.backgroundColor = [UIColor whiteColor];
    NSString *name = self.arrayRequest[indexPath.row][@"creator_name"];
    NSString *content = self.arrayRequest[indexPath.row][@"content"];
    NSUInteger length = name.length;
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:%@%li",name,content,(long)indexPath.row]];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.314 green:0.769 blue:1.000 alpha:1.000] range:NSMakeRange(0,length)];
    cell.textLabel.attributedText = str;
    
    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.textLabel.lineBreakMode = NSLineBreakByCharWrapping;
    cell.textLabel.numberOfLines = 3;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.backgroundColor = [UIColor colorWithWhite:0.949 alpha:1.000];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayRequest.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ReleasViewController *releaseVC = [[ReleasViewController alloc]init];
    releaseVC.peopleid  = self.copmodel.creator;
    [self.navigationController pushViewController:releaseVC animated:YES];
//    RIButtonItem *cancel = [RIButtonItem itemWithLabel:@"取消"];
//    RIButtonItem *subMit = [RIButtonItem itemWithLabel:@"确定" action:^{
//        NSLog(@"%@",@"确定方法执行");
//    }];
//    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"是否删除该出纳" message:nil cancelButtonItem:cancel otherButtonItems:subMit, nil];
//    [alertView show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)didrelease_Action:(UIButton *)sender {
    ReleasViewController *releaseVC = [[ReleasViewController alloc]init];
    releaseVC.peopleid  = self.copmodel.creator;
    [self.navigationController pushViewController:releaseVC animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
